import { useCallback, useRef } from 'react';
import { PositionType } from '@/types/canvas';
import config from '../config';

export default function usePosition() {
  const { current: collection } = useRef<PositionType[]>([]);
  // 生产随机坐标
  const getPosition = useCallback(() => {
    const splitWidthNum = config.canvas.width / config.model.width;
    const splitHeightNum = config.canvas.height / config.model.height - 6;
    return {
      x: ~~(Math.random() * splitWidthNum) * config.model.width,
      y: ~~(Math.random() * splitHeightNum) * config.model.height + 3 * config.model.height,
    };
  }, []);

  // 批量生产坐标
  const getCollectionPositions = useCallback(count => {
    const _collection = [] as PositionType[];
    for (let i = 0; i < count; i++) {
      while (true) {
        const position = getPosition();
        const isExist = collection.some(p => p.x === position.x && p.y === position.y);
        if (!isExist) {
          collection.push(position);
          _collection.push(position);
          break;
        }
      }
    }
    return _collection;
  }, []);

  return [collection, { getPosition, getCollectionPositions }] as const;
}
